//package com.github.llyb120.compiler.java;
//
//import cn.hutool.core.io.FileUtil;
//import cn.hutool.core.io.IoUtil;
//import cn.hutool.core.io.resource.ClassPathResource;
//import cn.hutool.core.lang.Snowflake;
//import cn.hutool.core.lang.func.Func1;
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.core.util.ZipUtil;
//import com.github.llyb120.ctrl.TestController;
//import com.github.llyb120.util.JarUtil;
//import lombok.SneakyThrows;
//import org.mdkt.compiler.InMemoryJavaCompiler;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import sun.nio.ch.IOUtil;
//
//import javax.tools.*;
//import java.io.File;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStreamWriter;
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Map;
//import java.util.regex.Matcher;
//
///**
// * @Author: Administrator
// * @Date: 7/26/2021 6:32 PM
// */
//@Deprecated
//@Component
//public class DynamicJavaCompiler {
//
//    static Snowflake snowflake = new Snowflake(0L, 0L);
//
//    private static String template;
//    private static String classPathDir = "";
//
//
//    @Autowired
//    public void init(TestController testController){
//        ClassPathResource resource = new ClassPathResource("javaTemplate.tpl");
//        try (InputStream is = resource.getStream()) {
//            template = IoUtil.read(is, StandardCharsets.UTF_8);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        String jarPath = getAppPath(DynamicJavaLoader.class);
//        if(jarPath.contains(".jar!")){
//            int pos = jarPath.indexOf(".jar");
//            jarPath = jarPath.substring(0, pos + ".jar".length());
//            File targetFile = new File(new File(jarPath).getParent(), "uncompressed");
//            if(targetFile.exists()){
//                FileUtil.del(targetFile);
//            }
//            targetFile.mkdirs();
//            ZipUtil.unzip(jarPath, targetFile.getAbsolutePath());
//            classPathDir = new File(targetFile.getAbsolutePath(), "BOOT-INF/classes").getAbsolutePath();
//        }
//
//        //test
////        testController.test2();
//    }
//
//    public static Class compile(DynamicCode code) {
//        String className = String.format("dy_%d", snowflake.nextId());
//        code.setClassName(className);
//        String src = StrUtil.replace(template, "\\$\\{([a-zA-Z0-9]+)\\}", new Func1<Matcher, String>() {
//            @Override
//            public String call(Matcher matcher) throws Exception {
//                String varName = matcher.group(1);
//                switch (varName) {
//                    case "imports":
//                        return code.getImports();
//                    case "mainCode":
//                        return code.getMainCode() + "\n;";
//                    case "insertBefore":
//                        return code.getInsertBefore();
//                    case "className":
//                        return code.getClassName();
//                }
//                return "";
//            }
//        });
//        className = "com.github.llyb120.dynamic.clz." + className;
//        Map<String, Class<?>> result = compileToByteCode(className, src);
//        if (result == null) {
//            throw new RuntimeException("编译错误，请检查源代码");
//        }
//        return result.get(className);
////        return CompileResult.builder()
////            .name(className)
////            .byteCode(result.get(className))
////            .build();
//    }
//
//    @SneakyThrows
//    private static Map<String, Class<?>> compileToByteCode(String javaName, String javaSrc) {
//        Map<String, Class<?>> res = InMemoryJavaCompiler.newInstance()
//            .useParentClassLoader(Thread.currentThread().getContextClassLoader())
//            .useOptions("-cp", classPathDir)
//            .addSource(javaName, javaSrc)
//            .compileAll();
//        return res;
//
////        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
////        StandardJavaFileManager stdManager = compiler.getStandardFileManager(null, null, null);
////        try {
////            stdManager.setLocation(
////                StandardLocation.CLASS_PATH,
////                Arrays.asList( new File( "C:\\Users\\Administrator\\Desktop\\project\\demo\\target\\demo-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes" ) )
////            );
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////        try (MemoryJavaFileManager manager = new MemoryJavaFileManager(stdManager)) {
////            JavaFileObject javaFileObject = manager.makeStringSource(javaName, javaSrc);
////            List<String> optionList = new ArrayList<String>();
////// set compiler's classpath to be same as the runtime's
////            optionList.addAll(Arrays.asList("-cp", "C:\\Users\\Administrator\\Desktop\\project\\demo\\target\\classes"));
////            OutputStreamWriter writer = new OutputStreamWriter(System.out);
//////            System.out.println(jar);
////            JavaCompiler.CompilationTask task = compiler.getTask(writer, manager, null, optionList, null, Arrays.asList(javaFileObject));
////            if (task.call())
////                return manager.getClassBytes();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//    }
//
//
//    public static String getAppPath(Class<?> cls) {
//        //检查用户传入的参数是否为空
//
//        if (cls == null)
//
//            throw new java.lang.IllegalArgumentException("参数不能为空！");
//
//
//        ClassLoader loader = cls.getClassLoader();
//
//        //获得类的全名，包括包名
//
//        String clsName = cls.getName();
//
//        //此处简单判定是否是Java基础类库，防止用户传入JDK内置的类库
//
//        if (clsName.startsWith("java.") || clsName.startsWith("javax.")) {
//            throw new java.lang.IllegalArgumentException("不要传送系统类！");
//
//        }
//
//        //将类的class文件全名改为路径形式
//
//        String clsPath = clsName.replace(".", "/") + ".class";
//
//
//        //调用ClassLoader的getResource方法，传入包含路径信息的类文件名
//
//        java.net.URL url = loader.getResource(clsPath);
//
//        //从URL对象中获取路径信息
//
//        String realPath = url.getPath();
//
//        //去掉路径信息中的协议名"file:"
//
//        int pos = realPath.indexOf("file:");
//
//        if (pos > -1) {
//            realPath = realPath.substring(pos + 5);
//
//        }
//
//        //去掉路径信息最后包含类文件信息的部分，得到类所在的路径
//
//        pos = realPath.indexOf(clsPath);
//
//        realPath = realPath.substring(0, pos - 1);
//
//        //如果类文件被打包到JAR等文件中时，去掉对应的JAR等打包文件名
//
//        if (realPath.endsWith("!")) {
//            realPath = realPath.substring(0, realPath.lastIndexOf("/"));
//
//        }
//
//        java.io.File file = new java.io.File(realPath);
//
//        realPath = file.getAbsolutePath();
//
//
//        try {
//
//            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
//
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//
//        }
//
//        return realPath;
//
//    }//getAppPath定义结束
//
//
//}
